import React from 'react'
import { Table,Icon,Modal,Popconfirm,Form,Input,Row,Col,DatePicker,Button,Message,Select,Upload} from 'antd';
const FormItem = Form.Item;
const Option = Select.Option;
import api from '../../../api/communityHouseUser';
import EditForm from '../../Form/CommunityHouseUser';
import CommunityCascader from '../../Cascader/CommunityCascader';

const { RangePicker } = DatePicker;
import moment from 'moment';

import PanelBox from '../../../components/PanelBox';
import {jsonToTree} from '../../../utils/tools'
import { reqToken } from "../../../utils/reqTools";
import { INTERFACE_CORE_URL } from '../../../api/config';

import '../../../style/antd-theme.less';
const pageRouter = '/community/houseUser';

export default class TablePage extends React.Component {
  state = {
    data: [],
    pagination: {
      pageSize:20,
      pageNum:1,
    },
    loading: false, 
    officeId:'',
    importUrl: '',
    exportUrl: '',
  };
  handleTableChange = (pagination, filters, sorter) => {
    pagination.pageNum=pagination.current;
    this.setState({pagination});
   
    this.fetch({...pagination});
  }
  fetch = (params) => {
    this.setState({ loading: true });
    api.get('/communityUser/getAll', { params}).then((data) => {
      const _data = data.data.list;
      const pagination = { ...this.state.pagination };
      pagination.total = data.data.total;
      this.setState({
        loading: false,
        data: _data,
        pagination,
      });
    });
  }

  componentDidMount = () =>{
    let user =this.props.profile.user;
    this.setState({
      userSession:user,
      officeId:user.officeId
      });
    this.fetch({ ...this.state.pagination });

  }
  componentWillMount() {
    this._isMounted = true;
    reqToken().then(res => {
      this._isMounted && this.setState({
        importUrl: INTERFACE_CORE_URL +'/api/communityMemberController/importExcel?token='+ res,
        exportUrl: INTERFACE_CORE_URL +'/api/communityMemberController/exportExcel?token='+ res,
      })
    });
  }
  componentWillUnmount() {
    this._isMounted = false;
  }

  add = () => {
    if(this.resetFields)this.resetFields();
    this.setState({
      isOpenModal: true,
      clearForm: false,
      titleName: '添加业主',
      rowRecord:false,
    });
  }
  edit = (record, event) => {
    if(this.resetFields)this.resetFields();
    this.setState({
      isOpenModal: true,
      clearForm: false,
      titleName: '修改业主',
      rowRecord: record 
    });
  }
  exportUser = () => {
    this.setState({
      exportIsOpenModal: true,
    });
  }
  importUser = ({ fileList }) => {
    if(fileList.length > 0 && typeof(fileList[0].response) != 'undefined'){
      let codes=fileList[0].response.code;
      if(codes == 0){
        this.fetch({ ...this.state.pagination });
        Message.success(`操作成功`);
      }else if(codes == 104){
        Message.error(`长时间未操作，请重新尝试`);
        this.props.history.replace(pageRouter);
      }
    }
   
  }
  changeExportUser = (value) => {
    this.setState({
      bulidId: value,
    });
  }
  exportUserOpion = () => {
    let b=this.state.bulidId;
    if( b && b.length != 2){
      Message.error("只能选择大楼导出");
      return;
    }
    if(b && b.length>0){
      let bulidId=b[b.length-1];
      window.location=this.state.exportUrl+'&buildId='+bulidId;
      this.close();
    }
  
  }
  close = () => {
    this.setState({
      isOpenModal: false,
      clearForm: true,
      exportIsOpenModal: false,
    });
  }
  refeshData = () => {
    this.fetch({ ...this.state.pagination });
  }

  initChildrenParams = (params) => {
    this.resetFields = params.resetFields;
  }


  render() {
    let columns = [{
      title: '房间名称',
      dataIndex: 'houseName',
    },{
      title: '业主姓名',
      dataIndex: 'name',
      width: '15%'
    },{
      title: '业主手机',
      dataIndex: 'mobile',
      width: '15%',
    },{
      title:'创建时间',
      dataIndex: 'create_date',
      width: '15%',
      sorter: true,
    },{
      title: '业主状态',
      dataIndex: 'state',
      width: '10%',
      render:(text, record, index) =>  {
        switch(record.state){
          case 0:
            return '禁用';
          case 1:
            return '启用';
          default:
            return '未知';
        }
      },
    }, {
      title: '操作',
      width: '10%',
      render: (text, record) => (
        <span>
        <a href="javascript:void(0)" onClick={this.edit.bind(this, record)}>修改</a>
        </span>
      ),
    }];
    return (
      <div>
        <SearchCostForm searchCostState={this.state} goSearch={this.handleTableChange} add={this.add} importUser={this.importUser} exportUser={this.exportUser}/>
        <PanelBox>
          <Table columns={columns}  dataSource={this.state.data}  pagination={this.state.pagination}
            loading={this.state.loading}  onChange={this.handleTableChange}  rowKey='id'
          />
        </PanelBox>
        <Modal
          title={this.state.titleName}
          visible={this.state.isOpenModal}
          onCancel={this.close}
          width={800}
          wrapClassName="vertical-center-modal"
          footer={null}
        >
          <EditForm userSession={this.state.userSession} rowRecord={this.state.rowRecord}  close={this.close} refeshData={this.refeshData} clearForm={this.state.clearForm}  callbackParent={this.initChildrenParams}/>
        </Modal>
        <Modal
          title="导出用户"
          visible={this.state.exportIsOpenModal}
          width={400}
          wrapClassName="vertical-center-modal"
          onOk={this.exportUserOpion}
          onCancel={this.close}
          okText="确认"
          cancelText="取消"
        >
            <CommunityCascader style={{width:'300px'}} changeOnSelect={false}  className="community-cascader" placeholder="请选择导出的大楼"  maxLevel="2"  pid={this.state.officeId}  onChange={this.changeExportUser}/>
            
        </Modal>
      </div>
    );
  }
}

    class SearchsForm extends React.Component {
   
      // 开始搜索
      goSearch = (e) => {
        let params=this.props.form.getFieldsValue();
        
        let _this=this.props;
        params.pageSize=_this.searchCostState.pagination.pageSize;
        params.pageNum =1;
        params.current =1;
        if(params.date.length > 0){
          params.startCreateDate=moment(params.date[0]).format("YYYY-MM-DD");
          params.endCreateDate=moment(params.date[1]).format("YYYY-MM-DD");
        }
        delete params.date;
        if(params.hasGive == -1){
         delete params.hasGive;
        }
        if(params.type == -1){
         delete params.type;
        }
        _this.goSearch(params);
     
      }

      srearchStyle = {
        labelCol: { span: 8},
        wrapperCol: { span: 14 },
      };
     
      render() {
        const { getFieldDecorator } = this.props.form;
        const formItemLayout = this.srearchStyle;
        return <Form onSubmit={this.goSearch} layout="inline" style={{marginBottom:'10px'}}>
          
          <FormItem {...formItemLayout} label="业主姓名" style={{marginBottom:'10px'}}>
            {getFieldDecorator('name' )(
              <Input type="text" placeholder="请输入业主姓名"/>
            )}
          </FormItem>
          
          <FormItem {...formItemLayout} label="业主电话">
            {getFieldDecorator('mobile' )(
              <Input type="text" placeholder="请输入业主电话"/>
            )}
          </FormItem>
          
          <FormItem {...formItemLayout} label="创建时间" style={{marginLeft:'-50px'}}>
            {getFieldDecorator('date' ,{ initialValue:[] } )(
              <RangePicker format="YYYY/MM/DD" />
            )}
          </FormItem>
          <FormItem  {...formItemLayout}   label="业主状态" style={{marginLeft:'4px'}}>
            {getFieldDecorator('state',{ initialValue:'' } )(
              <Select style={{ width: 139 }}>
                 <Option value="">全部</Option>
                <Option value="1">启用</Option>
                <Option value="0">禁用</Option>
              </Select>
            )}
          </FormItem>
          <FormItem>
            <Button type="primary" icon="search" htmlType="submit">搜索</Button>
          </FormItem> 
          <FormItem>
            <Button type="primary" onClick={this.props.add}>添加业主</Button>
          </FormItem>
          <FormItem>
            <Upload 
              action={this.props.searchCostState.importUrl}
              onChange={this.props.importUser}
              showUploadList={false}
            >
              <Button type="primary" >导入业主</Button>
            </Upload>
          </FormItem>
          <FormItem>
            <Button type="primary" onClick={this.props.exportUser}>导出业主</Button>
          </FormItem>
        </Form>
      }
    }
    const SearchCostForm = Form.create({})(SearchsForm);